package usercenter

import (
	"context"
	"database/sql"
	"fmt"
	"github.com/zeromicro/go-zero/core/stores/cache"
	"github.com/zeromicro/go-zero/core/stores/sqlx"
	"time"
)

var _ UserRewardLimitModel = (*customUserRewardLimitModel)(nil)

type (
	// UserRewardLimitModel is an interface to be customized, add more methods here,
	// and implement the added methods in customUserRewardLimitModel.
	UserRewardLimitModel interface {
		userRewardLimitModel
		InsertTrans(ctx context.Context, tx sqlx.Session, data *UserRewardLimit) (sql.Result, error)
		UpdateLuckyReward(ctx context.Context, tx sqlx.Session, uid, cnt int64, updateTime *time.Time) error
	}

	customUserRewardLimitModel struct {
		*defaultUserRewardLimitModel
	}
)

// NewUserRewardLimitModel returns a model for the database table.
func NewUserRewardLimitModel(conn sqlx.SqlConn, c cache.CacheConf, opts ...cache.Option) UserRewardLimitModel {
	return &customUserRewardLimitModel{
		defaultUserRewardLimitModel: newUserRewardLimitModel(conn, c, opts...),
	}
}

func (m *customUserRewardLimitModel) InsertTrans(ctx context.Context, tx sqlx.Session, data *UserRewardLimit) (sql.Result, error) {
	mumbaiUserRewardLimitUidKey := fmt.Sprintf("%s%v", cacheMumbaiUsercenterUserRewardLimitUidPrefix, data.Uid)
	ret, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("insert into %s (%s) values (?, ?, ?, ?, ?)", m.table, userRewardLimitRowsExpectAutoSet)
		return tx.ExecCtx(ctx, query, data.Uid, data.TodayLuckyRewardCnt, data.LuckyRewardUpdateTime, data.TodayLoginRewardCnt, data.LoginRewardUpdateTime)
	}, mumbaiUserRewardLimitUidKey)
	return ret, err
}

func (m *customUserRewardLimitModel) UpdateLuckyReward(ctx context.Context, tx sqlx.Session, uid, cnt int64, updateTime *time.Time) error {
	mumbaiUserRewardLimitUidKey := fmt.Sprintf("%s%v", cacheMumbaiUsercenterUserRewardLimitUidPrefix, uid)
	_, err := m.ExecCtx(ctx, func(ctx context.Context, conn sqlx.SqlConn) (result sql.Result, err error) {
		query := fmt.Sprintf("update %s set today_lucky_reward_cnt=?, lucky_reward_update_time=? where uid = ?", m.table)
		return tx.ExecCtx(ctx, query, cnt, updateTime, uid)
	}, mumbaiUserRewardLimitUidKey)
	return err
}
